package controllers

import (
	"errors"
	"github.com/dotbalo/kubeutils/kubeutils"
	"github.com/gin-gonic/gin"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"net/http"
	"oam-manage-backend/config"
	"oam-manage-backend/utils/logs"
)

// 全局的数据结构
type BasicInfo struct {
	ClusterId  string      `json:"clusterId" form:"clusterId"`
	Namespace  string      `json:"namespace" form:"namespace"`
	Name       string      `json:"name" form:"name"`
	Item       interface{} `json:"item" form:"item"`
	DeleteList []string    `json:"deleteList"`
}

type Info struct {
	BasicInfo
	ReturnData    config.ReturnData
	LabelSelector string `json:"labelSelector"`
	FieldSelector string `json:"fieldSelector"`
	// 判断是否强制删除
	Force bool `json:"force"`
}

func NewInfo(r *gin.Context, info *Info, returnDataMsg string) (kubeconfig string) {
	// 获取请求类型
	requestMethod := r.Request.Method
	var err error
	info.ReturnData.Message = returnDataMsg
	info.ReturnData.Status = 200
	if requestMethod == "GET" || requestMethod == "DELETE" {
		err = r.ShouldBindQuery(&info)
	} else if requestMethod == "POST" || requestMethod == "PUT" {
		err = r.ShouldBindJSON(&info)
	} else {
		err = errors.New("不支持的请求类型")
	}
	logs.Deubg(map[string]interface{}{"basicInfo": info}, "数据绑定结果")
	if err != nil {
		msg := "请求出错:" + err.Error()
		info.ReturnData.Message = msg
		info.ReturnData.Status = 400
		logs.Error(nil, msg)
		r.JSON(http.StatusOK, info.ReturnData)
		return
	}

	// 获取kubeconfig
	kubeconfig = config.ClusterKubeconfig[info.ClusterId]
	return kubeconfig
}

func (b *Info) Create(r *gin.Context, kubeUtilsInterface kubeutils.KubeUtilser) {
	err := kubeUtilsInterface.Create(b.Namespace)
	if err != nil {
		msg := "创建失败:" + err.Error()
		b.ReturnData.Message = msg
		b.ReturnData.Status = 400
		logs.Error(nil, msg)
	}
	r.JSON(http.StatusOK, b.ReturnData)
}

func (b *Info) Update(r *gin.Context, kubeUtilsInterface kubeutils.KubeUtilser) {
	err := kubeUtilsInterface.Update(b.Namespace)
	if err != nil {
		msg := "更新失败:" + err.Error()
		b.ReturnData.Message = msg
		b.ReturnData.Status = 400
		logs.Error(nil, msg)
	}
	r.JSON(http.StatusOK, b.ReturnData)
}

func (b *Info) List(r *gin.Context, kubeUtilsInterface kubeutils.KubeUtilser) {
	items, err := kubeUtilsInterface.List(b.Namespace, b.LabelSelector, b.FieldSelector)
	if err != nil {
		msg := "查询失败:" + err.Error()
		b.ReturnData.Message = msg
		b.ReturnData.Status = 400
		logs.Error(nil, msg)
	} else {
		b.ReturnData.Data = make(map[string]interface{})
		b.ReturnData.Data["items"] = items
	}
	r.JSON(http.StatusOK, b.ReturnData)
}

func (b *Info) Get(r *gin.Context, kubeUtilsInterface kubeutils.KubeUtilser) {
	item, err := kubeUtilsInterface.Get(b.Namespace, b.Name)
	if err != nil {
		msg := "查询失败:" + err.Error()
		b.ReturnData.Message = msg
		b.ReturnData.Status = 400
		logs.Error(nil, msg)
	} else {
		b.ReturnData.Data = make(map[string]interface{})
		b.ReturnData.Data["item"] = item
	}
	r.JSON(http.StatusOK, b.ReturnData)
}

func (b *Info) Delete(r *gin.Context, kubeUtilsInterface kubeutils.KubeUtilser) {
	var gracePeriodSeconds int64
	if b.Force {
		// 强制删除
		var s int64 = 0
		gracePeriodSeconds = s
	}
	err := kubeUtilsInterface.Delete(b.Namespace, b.Name, &gracePeriodSeconds)
	if err != nil {
		msg := "删除失败:" + err.Error()
		b.ReturnData.Message = msg
		b.ReturnData.Status = 400
		logs.Error(nil, msg)
	}
	r.JSON(http.StatusOK, b.ReturnData)
}

func (b *Info) DeleteList(r *gin.Context, kubeUtilsInterface kubeutils.KubeUtilser) {
	var gracePeriodSeconds int64
	if b.Force {
		// 强制删除
		var s int64 = 0
		gracePeriodSeconds = s
	}
	err := kubeUtilsInterface.DeleteList(b.Namespace, b.BasicInfo.DeleteList, &gracePeriodSeconds)
	if err != nil {
		msg := "删除失败:" + err.Error()
		b.ReturnData.Message = msg
		b.ReturnData.Status = 400
		logs.Error(nil, msg)
	}
	r.JSON(http.StatusOK, b.ReturnData)
}

func BasicInit(r *gin.Context, item interface{}) (clientset *kubernetes.Clientset, baseicInfo BasicInfo, err error) {
	baseicInfo = BasicInfo{}
	baseicInfo.Item = item
	// 获取请求类型
	requestMethod := r.Request.Method
	if requestMethod == "GET" || requestMethod == "DELETE" {
		err = r.ShouldBindQuery(&baseicInfo)
	} else if requestMethod == "POST" || requestMethod == "PUT" {
		err = r.ShouldBindJSON(&baseicInfo)
	} else {
		err = errors.New("不支持的请求类型")
	}
	logs.Deubg(map[string]interface{}{"basicInfo": baseicInfo}, "数据绑定结果")
	if err != nil {
		msg := "请求出错:" + err.Error()
		return nil, baseicInfo, errors.New(msg)
	}
	if baseicInfo.Namespace == "" {
		baseicInfo.Namespace = "default"
	}
	// 获取kubeconfig
	kubeconfig := config.ClusterKubeconfig[baseicInfo.ClusterId]
	restConfig, err := clientcmd.RESTConfigFromKubeConfig([]byte(kubeconfig))
	if err != nil {
		msg := "解析kubeconfig错误:" + err.Error()
		return nil, baseicInfo, errors.New(msg)
	}
	clientset, err = kubernetes.NewForConfig(restConfig)
	if err != nil {
		msg := "创建clientSet失败:" + err.Error()
		return nil, baseicInfo, errors.New(msg)
	}
	return clientset, baseicInfo, nil
}
